package com.gmail.at.vssabinin.train_transport_system_part1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import command.CommandFactory;

/**
 * 
 * This class check's received data from client and work with clients request
 * it uses {@link CommandFactory} to determine which command was received.
 *
 */
public class Worker implements Runnable {

	// protocol of network messages
	private Protocol protocol = new Protocol();
	
	// factory which produces command objects according to the type of message
	private CommandFactory commandFactory = new CommandFactory();
	
	private ReceivedData receivedData = null;
	
	public Worker (ReceivedData received) {
		this.receivedData = received;
	}
	
	// logger
	private Logger logger = LoggerFactory.getLogger("Worker");
	
	public void run() {	
		/* 
		 * get a new task given by constructor, and check it's type, get the class which will handle 
		 * the given request
		 * 
		 * check's that received data from client is not null
		 */		
		if (receivedData != null) {
			Protocol.Message message = this.protocol.decodeMessage(receivedData.data);
			this.logger.info("Calling a new command with the given header: " 
					+ message.getType());
			commandFactory.factory(message.getType()).execute(receivedData);
		}				
				
	}
}